package com.person.jc.web.test.inspect;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.person.jc.common.Constants;
import com.person.jc.entity.TsUser;
import com.person.jc.service.base.device.BdDevicePartsService;
import com.person.jc.service.service.BsOrderService;
import com.person.jc.service.test.inspect.BsReconditionLogService;
import com.person.jc.service.test.inspect.BsRepairRegLogService;
import com.person.jc.utils.DateUtils;
import com.person.jc.utils.JsonMapper;
import com.person.jc.utils.Servlets;
import com.person.jc.utils.SessionKit;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * fcl我的检测任务
 */
//TODO 我的检测任务
public class MyTestingController extends Controller {

	public void init(){
		setAttr("menuId", getPara("menuId"));
		render("main.jsp");
	}
	
	public void list(){
		Map<String, Object> map = Servlets.getParametersStartingWith(getRequest(), "p_");
		TsUser tsUser = (TsUser)SessionKit.get().getAttribute(Constants.LOGIN_USER);
		map.put("optUser", tsUser.getUserId());
		map.put("orderType","1");
		//map.put("flow", Constants.FLOW_JCFP);
		map.put("flag","testing");
		List<Record> list = BsRepairRegLogService.me.getList(map);
		setAttr("list", list);
		render("list.jsp");
	}
	
	/**
	 * 首页我的检测任务个数
	 */
	public void getMyTestingCount(){
		Map<String, Object> map = Servlets.getParametersStartingWith(getRequest(), "p_");
		TsUser tsUser = (TsUser)SessionKit.get().getAttribute(Constants.LOGIN_USER);
		map.put("userId", tsUser.getUserId());
		List<Record> list = BsRepairRegLogService.me.getMyTestingCount(map);
		setAttr("list", list);
		render("indexTesting.jsp");
	}
	
	
	
	public void viewList(){
		Map<String, Object> map = Servlets.getParametersStartingWith(getRequest(), "p_");
		TsUser tsUser = (TsUser)SessionKit.get().getAttribute(Constants.LOGIN_USER);
		map.put("userId", tsUser.getUserId());
		map.put("orderType","1");
		List<Record> list = BsRepairRegLogService.me.getViewList(map);
		setAttr("list", list);
		setAttr("obj", map);
		render("viewList.jsp");
	}
	
	public void edit(){

		Map<String, Object> map = Servlets.getParametersStartingWith(getRequest(), "p_");
		map.put("orderType","1");
		List<Record> list = BsRepairRegLogService.me.getViewList(map);
		List<Map<String, String>> data = new ArrayList<Map<String,String>>();
		if(list!=null && list.size()>0){
			for (Record record : list) {
				Object recId = record.get("original_record");
				if(null==recId || recId.toString().equals("")){
					Map<String, String> dataMap = new HashMap<String, String>();
					dataMap.put("name", record.getStr("device_name"));
					dataMap.put("value", record.getStr("device_no"));
					data.add(dataMap);
				}else{
					if(record.get("device_type").toString().equals("3")){ //设备类型为3是气检仪，气检仪才有多个原始记录单
						String gasType=record.get("gas_type").toString();
						String[] gasTypeArray=gasType.split(",");
						String[] recIdArray=recId.toString().split(",");
						int num=0;
						for(String str:recIdArray){
							if(StringUtils.isNotBlank(str)){
								num++;
							}
						}
						if(num<gasTypeArray.length){
							Map<String, String> dataMap = new HashMap<String, String>();
							dataMap.put("name", record.getStr("device_name"));
							dataMap.put("value", record.getStr("device_no"));
							data.add(dataMap);
						}
					}
				}
			}
		}
		String resultText = JsonMapper.nonDefaultMapper().toJson(data);

		setAttr("inspectDate",DateUtils.getDate());
		setAttr("obj", map);
		setAttr("data", resultText);
		render("edit.jsp");
	}
	
	public void getEquipment(){
		Map<String, Object> map = Servlets.getParametersStartingWith(getRequest(), "p_");
		map.put("opflag", "eq");
		map.put("orderType","1");
		List<Record> list = BsRepairRegLogService.me.getViewList(map);
		String resultText = "none";
		if(list!=null && !list.isEmpty()){
			resultText = JsonMapper.nonDefaultMapper().toJson(list.get(0));
		}
		renderText(resultText);
	}
	
	@Before(Tx.class)
	public void save(){
		Map<String, Object> map = Servlets.getParametersStartingWith(getRequest(), "p_");
		TsUser tsUser = (TsUser)SessionKit.get().getAttribute(Constants.LOGIN_USER);
		map.put("optUser", tsUser.getUserId());
		
		String logId =  BsRepairRegLogService.me.save(map);
		map.put("logId",logId);
		if(!"exist".equals(logId)){
			//根据类型为气体并且和种类数，事先定义好original_record的路径段用，隔开
			if (map.get("deviceType").equals("3") && map.get("gasType") != null && !map.get("gasType").equals("")) {
				String[] gasTypeArray = map.get("gasType").toString().split(",");
				String str = " ";
				for (int i = 1; i < gasTypeArray.length; i++) {
					str += ", ";
				}
				map.put("originalRecord", str);
				map.put("scopes",str);

			}

			BsReconditionLogService.me.save(map);
			/*
			 * 判断订单是否已检查完，检查完的更新订单FLOWID; 得检查原始记录单都完成了才可以推向证书
			 */
//			String orderId = (String) map.get("orderId");
//			Integer num = BsRepairRegLogService.me.getUnInspectsNum(orderId);
//			if(num == 0){
//				BsOrderService.me.updateFlow(orderId, Constants.FLOW_WX_WXRW);
//			}
		}
		renderText("success");

	}
	
	public void chooseParts(){
		Map<String,Object> map = new HashMap<String, Object>();
		String partsCode = getPara("ec_f_parts_code");
		String partsName = getPara("ec_f_parts_name");
		String partsIds = getPara("partsIds");
		String otherIds = getPara("otherIds");
		String op = getPara("op");
		map.put("partsCode", partsCode);
		map.put("partsName", partsName);
		map.put("partsIds", partsIds);
		map.put("otherIds", otherIds);
		map.put("partsStatus", "0");
		map.put("op", op);
		List<Record> list = BdDevicePartsService.me.getList(map);
		setAttr("partsList", list);
		setAttr("obj", map);
		render("chooseParts.jsp");
	}
	
	
	/*
	 * 重新分配配件
	 */
	public void doChangeParts(){
		String logId = getPara("logId");
		String faultId = getPara("faultId");
		String partsId = getPara("partsId");
		//1. 获取预占配件列表，重置配件状态
		List<Record> parts = BsRepairRegLogService.me.getDetail(logId, faultId);
		String[] partsArr = new String[parts.size()];
		for (int i=0; i<parts.size(); i++) {
			partsArr[i] = String.valueOf(parts.get(i).get("parts_id"));
		}
		BdDevicePartsService.me.update(partsArr, 0);
		
		//2. 删除检测明细历史记录
		BsRepairRegLogService.me.delDetail(logId, faultId);
		
		//3. 保存检测明细
		String[] pid = partsId.split(",");
		Object[][] params = new Object[pid.length][3];
		for (int j = 0; j < pid.length; j++) {
			params[j][0] = logId;
			params[j][1] = faultId;
			params[j][2] = pid[j];
		}
		BsRepairRegLogService.me.saveDetail(logId, params, pid.length);
		// 配件预占用
		BdDevicePartsService.me.update(pid, 1);
		renderText("success");
	}
}
